// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const { collections = ['all'] } = event
  const wxContext = cloud.getWXContext()
  
  try {
    let result = {}
    
    // 初始化检查项
    if (collections.includes('all') || collections.includes('checkItems')) {
      result.checkItems = await initCheckItems()
    }
    
    // 初始化用户
    if (collections.includes('all') || collections.includes('users')) {
      result.users = await initUsers(wxContext.OPENID)
    }
    
    // 初始化寝室
    if (collections.includes('all') || collections.includes('dorms')) {
      result.dorms = await initDorms()
    }
    
    // 初始化检查记录
    if (collections.includes('all') || collections.includes('checks')) {
      result.checks = await initChecks()
    }
    
    // 初始化整改工单
    if (collections.includes('all') || collections.includes('tasks')) {
      result.tasks = await initTasks()
    }
    
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error(error)
    return {
      success: false,
      error
    }
  }
}

// 初始化检查项
async function initCheckItems() {
  try {
    // 清空集合
    await clearCollection('checkItems')
    
    // 检查项数据
    const checkItems = [
      {
        name: "地面清洁",
        description: "地面无垃圾、无明显灰尘",
        maxScore: 30,
        weight: 0.3,
        category: "环境卫生",
        standard: "地面整洁，无垃圾，无明显灰尘，拖把摆放整齐",
        isRequired: true,
        order: 1,
        createTime: new Date(),
        updateTime: new Date(),
        isActive: true
      },
      {
        name: "物品摆放",
        description: "个人物品摆放整齐有序",
        maxScore: 25,
        weight: 0.25,
        category: "物品摆放",
        standard: "床铺整洁，物品摆放有序，书籍整齐",
        isRequired: true,
        order: 2,
        createTime: new Date(),
        updateTime: new Date(),
        isActive: true
      },
      {
        name: "垃圾分类",
        description: "垃圾分类正确，及时清理",
        maxScore: 20,
        weight: 0.2,
        category: "环境卫生",
        standard: "垃圾桶内垃圾分类正确，及时清理，不超过2/3容量",
        isRequired: true,
        order: 3,
        createTime: new Date(),
        updateTime: new Date(),
        isActive: true
      },
      {
        name: "卫生间整洁",
        description: "卫生间无异味，设施清洁",
        maxScore: 15,
        weight: 0.15,
        category: "环境卫生",
        standard: "卫生间无异味，地面干燥，洗漱用品摆放整齐",
        isRequired: true,
        order: 4,
        createTime: new Date(),
        updateTime: new Date(),
        isActive: true
      },
      {
        name: "安全隐患",
        description: "无违规电器，无安全隐患",
        maxScore: 10,
        weight: 0.1,
        category: "安全",
        standard: "无违规电器，线路整齐，无消防隐患",
        isRequired: true,
        order: 5,
        createTime: new Date(),
        updateTime: new Date(),
        isActive: true
      }
    ]
    
    // 添加数据
    const checkItemIds = []
    for (const item of checkItems) {
      const result = await db.collection('checkItems').add({
        data: item
      })
      checkItemIds.push(result._id)
    }
    
    return checkItemIds
  } catch (error) {
    console.error('初始化检查项失败', error)
    throw error
  }
}

// 初始化用户
async function initUsers(currentUserOpenid) {
  try {
    // 清空集合
    await clearCollection('users')
    
    // 用户数据
    const users = [
      // 系统管理员
      {
        openid: currentUserOpenid, // 当前用户为管理员
        name: "系统管理员",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/default-avatar.png",
        role: "管理员",
        phone: "13800000000",
        createTime: new Date()
      },
      // 宿管
      {
        openid: "dormManager1",
        name: "宿管张老师",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/avatar-manager1.png",
        role: "宿管",
        building: ["1", "2"],
        phone: "13811111111",
        createTime: new Date()
      },
      {
        openid: "dormManager2",
        name: "宿管李老师",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/avatar-manager2.png",
        role: "宿管",
        building: ["3", "4"],
        phone: "13822222222",
        createTime: new Date()
      },
      // 学生
      {
        openid: "student1",
        name: "王小明",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/avatar-student1.png",
        role: "学生",
        building: "1",
        roomNo: "101",
        phone: "13833333333",
        createTime: new Date()
      },
      {
        openid: "student2",
        name: "李小红",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/avatar-student2.png",
        role: "学生",
        building: "1",
        roomNo: "101",
        phone: "13844444444",
        createTime: new Date()
      },
      {
        openid: "student3",
        name: "张小强",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/avatar-student3.png",
        role: "学生",
        building: "1",
        roomNo: "101",
        phone: "13855555555",
        createTime: new Date()
      },
      {
        openid: "student4",
        name: "赵小丽",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/avatar-student4.png",
        role: "学生",
        building: "1",
        roomNo: "101",
        phone: "13866666666",
        createTime: new Date()
      },
      {
        openid: "student5",
        name: "陈小伟",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/avatar-student5.png",
        role: "学生",
        building: "1",
        roomNo: "102",
        phone: "13877777777",
        createTime: new Date()
      },
      {
        openid: "student6",
        name: "郑小华",
        avatar: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/avatar-student6.png",
        role: "学生",
        building: "2",
        roomNo: "201",
        phone: "13888888888",
        createTime: new Date()
      }
    ]
    
    // 添加数据
    const userIds = []
    for (const user of users) {
      const result = await db.collection('users').add({
        data: user
      })
      userIds.push(result._id)
    }
    
    return userIds
  } catch (error) {
    console.error('初始化用户失败', error)
    throw error
  }
}

// 初始化寝室
async function initDorms() {
  try {
    // 清空集合
    await clearCollection('dorms')
    
    // 寝室数据
    const dorms = [
      {
        building: "1",
        roomNo: "101",
        members: ["student1", "student2", "student3", "student4"],
        monitorId: "student1",
        currentScore: 95,
        scoreHistory: [
          {
            date: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前
            score: 93,
            
          },
          {
            date: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000), // 14天前
            score: 90,
            
          }
        ],
        images: [
          "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/dorm-1-101-1.jpg",
          "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/dorm-1-101-2.jpg"
        ],
        medals: ["优秀寝室", "卫生标兵"],
        qrCodeUrl: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/qrcode-1-101.jpg",
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        building: "1",
        roomNo: "102",
        members: ["student5"],
        monitorId: "student5",
        currentScore: 88,
        scoreHistory: [
          {
            date: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前
            score: 85,
            
          }
        ],
        images: [
          "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/dorm-1-102-1.jpg"
        ],
        medals: [],
        qrCodeUrl: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/qrcode-1-102.jpg",
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        building: "2",
        roomNo: "201",
        members: ["student6"],
        monitorId: "student6",
        currentScore: 55, // 低于60分，需要整改
        scoreHistory: [
          {
            date: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前
            score: 52,
            
          }
        ],
        images: [
          "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/dorm-2-201-1.jpg"
        ],
        medals: [], // 不合格宿舍不应有勋章
        qrCodeUrl: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/qrcode-2-201.jpg",
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        building: "2",
        roomNo: "202",
        members: [],
        currentScore: 92,
        scoreHistory: [
          {
            date: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前
            score: 90,
          }
        ],
        images: [
          "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/dorm-2-202-1.jpg"
        ],
        medals: ["进步最快"],
        qrCodeUrl: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/qrcode-2-202.jpg",
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        building: "3",
        roomNo: "301",
        members: [],
        currentScore: 97,
        scoreHistory: [
          {
            date: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前
            score: 96,
            
          }
        ],
        images: [
          "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/dorm-3-301-1.jpg"
        ],
        medals: ["优秀寝室"],
        qrCodeUrl: "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/qrcode-3-301.jpg",
        createTime: new Date(),
        updateTime: new Date()
      }
    ]
    
    // 添加数据
    const dormIds = []
    for (const dorm of dorms) {
      const result = await db.collection('dorms').add({
        data: dorm
      })
      dormIds.push(result._id)
    }
    
    return dormIds
  } catch (error) {
    console.error('初始化寝室失败', error)
    throw error
  }
}

// 初始化检查记录
async function initChecks() {
  try {
    // 清空集合
    await clearCollection('checks')
    
    // 检查记录数据
    const checks = [
      {
        dormId: "will_be_replaced", // 在后续查询中替换
        building: "1",
        roomNo: "101",
        checkerId: "dormManager1",
        checkerName: "宿管张老师",
        checkDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000), // 1天前
        totalScore: 95,
        items: [
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "地面清洁",
            score: 28,
            maxScore: 30,
            images: ["cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/check-1-101-floor.jpg"],
            comment: "地面有少量灰尘"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "物品摆放",
            score: 25,
            maxScore: 25,
            images: [],
            comment: "物品摆放整齐"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "垃圾分类",
            score: 18,
            maxScore: 20,
            images: [],
            comment: "垃圾已清理"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "卫生间整洁",
            score: 14,
            maxScore: 15,
            images: [],
            comment: "卫生间干净整洁"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "安全隐患",
            score: 10,
            maxScore: 10,
            images: [],
            comment: "无安全隐患"
          }
        ],
        comment: "总体表现优秀，继续保持",
        status: "已完成",
        createTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
        updateTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000)
      },
      {
        dormId: "will_be_replaced", // 在后续查询中替换
        building: "1",
        roomNo: "102",
        checkerId: "dormManager1",
        checkerName: "宿管张老师",
        checkDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000), // 1天前
        totalScore: 88,
        items: [
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "地面清洁",
            score: 26,
            maxScore: 30,
            images: ["cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/check-1-102-floor.jpg"],
            comment: "地面有灰尘"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "物品摆放",
            score: 23,
            maxScore: 25,
            images: [],
            comment: "物品基本摆放整齐"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "垃圾分类",
            score: 15,
            maxScore: 20,
            images: ["cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/check-1-102-trash.jpg"],
            comment: "垃圾未分类"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "卫生间整洁",
            score: 14,
            maxScore: 15,
            images: [],
            comment: "卫生间基本整洁"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "安全隐患",
            score: 10,
            maxScore: 10,
            images: [],
            comment: "无安全隐患"
          }
        ],
        comment: "垃圾需要及时分类",
        status: "已完成",
        createTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
        updateTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000)
      },
      {
        dormId: "will_be_replaced", // 在后续查询中替换
        building: "2",
        roomNo: "201",
        checkerId: "dormManager1",
        checkerName: "宿管张老师",
        checkDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000), // 1天前
        totalScore: 55, // 分数低于60，需要整改
        items: [
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "地面清洁",
            score: 20,
            maxScore: 30,
            images: ["cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/check-2-201-floor.jpg"],
            comment: "地面比较脏，有垃圾"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "物品摆放",
            score: 18,
            maxScore: 25,
            images: ["cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/check-2-201-stuff.jpg"],
            comment: "物品乱放"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "垃圾分类",
            score: 15,
            maxScore: 20,
            images: [],
            comment: "垃圾未分类"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "卫生间整洁",
            score: 12,
            maxScore: 15,
            images: [],
            comment: "卫生间尚可"
          },
          {
            itemId: "will_be_replaced", // 在后续查询中替换
            name: "安全隐患",
            score: 10,
            maxScore: 10,
            images: [],
            comment: "无安全隐患"
          }
        ],
        comment: "需要整改，清洁房间，整理物品",
        status: "已完成",
        createTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
        updateTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000)
      }
    ]
    
    // 获取dormId
    const dormList = await db.collection('dorms').get()
    const dormMap = {}
    dormList.data.forEach(dorm => {
      dormMap[`${dorm.building}-${dorm.roomNo}`] = dorm._id
    })
    
    // 获取checkItemId
    const checkItemList = await db.collection('checkItems').get()
    const checkItemMap = {}
    checkItemList.data.forEach(item => {
      checkItemMap[item.name] = item._id
    })
    
    // 替换ID
    checks.forEach(check => {
      check.dormId = dormMap[`${check.building}-${check.roomNo}`]
      check.items.forEach(item => {
        item.itemId = checkItemMap[item.name]
      })
    })
    
    // 添加数据
    const checkIds = []
    for (const check of checks) {
      const result = await db.collection('checks').add({
        data: check
      })
      checkIds.push(result._id)
    }
    
    return checkIds
  } catch (error) {
    console.error('初始化检查记录失败', error)
    throw error
  }
}

// 初始化整改工单
async function initTasks() {
  try {
    // 清空集合
    await clearCollection('tasks')
    
    // 获取dormId和分数
    const dormList = await db.collection('dorms').get()
    const dormMap = {}
    const dormScores = {}
    dormList.data.forEach(dorm => {
      dormMap[`${dorm.building}-${dorm.roomNo}`] = dorm._id
      dormScores[`${dorm.building}-${dorm.roomNo}`] = dorm.currentScore
    })
    
    // 获取checkId
    const checkList = await db.collection('checks').get()
    const checkMap = {}
    checkList.data.forEach(check => {
      checkMap[`${check.building}-${check.roomNo}`] = check._id
    })
    
    // 整改工单数据 - 只为分数低于60分的寝室创建整改工单
    const tasks = []
    
    // 检查2栋201寝室的分数，如果低于60分则创建整改工单
    if (dormScores["2-201"] < 60) {
      tasks.push({
        dormId: dormMap["2-201"],
        building: "2",
        roomNo: "201",
        roomInfo: "2栋201寝室",
        checkId: checkMap["2-201"],
        title: "需要清洁地面和整理物品",
        description: "本次检查发现地面比较脏，有垃圾；物品乱放，请及时整改",
        requirements: "1. 清洁地面，清理垃圾\n2. 整理物品，摆放整齐",
        images: [
          "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/check-2-201-floor.jpg",
          "cloud://cloud1-1g8ou1sf692364f2.636c-cloud1-1g8ou1sf692364f2-1324030359/check-2-201-stuff.jpg"
        ],
        creatorId: "dormManager1",
        creatorName: "宿管张老师",
        createTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000), // 1天前
        deadline: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2天后
        status: "待整改",
        notifyStatus: ["已通知"]
      })
    }
    
    // 添加数据
    const taskIds = []
    for (const task of tasks) {
      const result = await db.collection('tasks').add({
        data: task
      })
      taskIds.push(result._id)
    }
    
    return taskIds
  } catch (error) {
    console.error('初始化整改工单失败', error)
    throw error
  }
}

// 清空集合
async function clearCollection(collectionName) {
  try {
    // 获取集合中的所有记录
    const { data } = await db.collection(collectionName).get()
    
    // 如果有数据，则批量删除
    if (data.length > 0) {
      const batchTimes = Math.ceil(data.length / 100)
      
      for (let i = 0; i < batchTimes; i++) {
        const batch = data.slice(i * 100, (i + 1) * 100)
        const ids = batch.map(item => item._id)
        
        await db.collection(collectionName).where({
          _id: _.in(ids)
        }).remove()
      }
    }
    
    return true
  } catch (error) {
    console.error(`清空集合 ${collectionName} 失败`, error)
    throw error
  }
} 